<template>
  <div class="courses-container">
    <div class="page-header">
      <h2>课程管理</h2>
      <el-button v-if="userStore.isAdmin || userStore.isTeacher" type="primary" @click="handleAddCourse">
        <el-icon><Plus /></el-icon>添加课程
      </el-button>
    </div>

    <el-card class="box-card">
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="课程编号">
            <el-input v-model="searchForm.courseId" placeholder="请输入课程编号" clearable />
          </el-form-item>
          <el-form-item label="课程名称">
            <el-input v-model="searchForm.name" placeholder="请输入课程名称" clearable />
          </el-form-item>
          <el-form-item label="课程类型">
            <el-select v-model="searchForm.type" placeholder="请选择课程类型" clearable>
              <el-option
                v-for="item in courseTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="courseList" style="width: 100%" border>
        <el-table-column prop="courseId" label="课程编号" width="120" />
        <el-table-column prop="name" label="课程名称" width="150" />
        <el-table-column prop="typeName" label="课程类型" width="120">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.type)">
              {{ scope.row.typeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="credit" label="学分" width="80" />
        <el-table-column prop="hours" label="学时" width="80" />
        <el-table-column prop="teacher" label="授课教师" width="120" />
        <el-table-column prop="semester" label="开课学期" width="120" />
        <el-table-column prop="description" label="课程描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <template v-if="userStore.isAdmin || userStore.isTeacher">
              <el-button size="small" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
            <span v-else>无操作权限</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑课程对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加课程' : '编辑课程'"
      width="50%"
    >
      <el-form
        ref="courseFormRef"
        :model="courseForm"
        :rules="rules"
        label-width="100px"
        style="max-width: 600px"
      >
        <el-form-item label="课程编号" prop="courseId">
          <el-input v-model="courseForm.courseId" placeholder="请输入课程编号" />
        </el-form-item>
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="courseForm.name" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程类型" prop="type">
          <el-select v-model="courseForm.type" placeholder="请选择课程类型">
            <el-option
              v-for="item in courseTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学分" prop="credit">
          <el-input-number v-model="courseForm.credit" :min="0.5" :max="10" :step="0.5" />
        </el-form-item>
        <el-form-item label="学时" prop="hours">
          <el-input-number v-model="courseForm.hours" :min="8" :max="120" :step="2" />
        </el-form-item>
        <el-form-item label="授课教师" prop="teacher">
          <el-input v-model="courseForm.teacher" placeholder="请输入授课教师" />
        </el-form-item>
        <el-form-item label="开课学期" prop="semester">
          <el-select v-model="courseForm.semester" placeholder="请选择开课学期">
            <el-option
              v-for="item in semesters"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input
            v-model="courseForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入课程描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useUserStore } from '../stores/user';

// 初始化用户存储
const userStore = useUserStore();

// 搜索表单
const searchForm = reactive({
  courseId: '',
  name: '',
  type: '',
});

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 课程类型
const courseTypes = ref([
  { value: '1', label: '必修课' },
  { value: '2', label: '选修课' },
  { value: '3', label: '公共课' },
  { value: '4', label: '专业课' },
]);

// 学期列表
const semesters = ref([
  { value: '2023-2024-1', label: '2023-2024学年第一学期' },
  { value: '2023-2024-2', label: '2023-2024学年第二学期' },
  { value: '2024-2025-1', label: '2024-2025学年第一学期' },
  { value: '2024-2025-2', label: '2024-2025学年第二学期' },
]);

// 课程列表
const courseList = ref([
  {
    id: 1,
    courseId: 'CS101',
    name: '计算机导论',
    type: '1',
    typeName: '必修课',
    credit: 3,
    hours: 48,
    teacher: '张教授',
    semester: '2023-2024-1',
    description: '本课程介绍计算机科学的基本概念和原理，包括计算机历史、硬件、软件、网络等内容。',
  },
  {
    id: 2,
    courseId: 'CS102',
    name: '程序设计基础',
    type: '1',
    typeName: '必修课',
    credit: 4,
    hours: 64,
    teacher: '李教授',
    semester: '2023-2024-1',
    description: '本课程介绍程序设计的基本概念和方法，使用C语言作为教学语言，培养学生的编程思维和能力。',
  },
  {
    id: 3,
    courseId: 'CS201',
    name: '数据结构',
    type: '1',
    typeName: '必修课',
    credit: 4,
    hours: 64,
    teacher: '王教授',
    semester: '2023-2024-2',
    description: '本课程介绍常用的数据结构和算法，包括数组、链表、栈、队列、树、图等，以及相关的算法设计与分析。',
  },
  {
    id: 4,
    courseId: 'CS301',
    name: '操作系统',
    type: '4',
    typeName: '专业课',
    credit: 3.5,
    hours: 56,
    teacher: '赵教授',
    semester: '2024-2025-1',
    description: '本课程介绍操作系统的基本概念、原理和实现方法，包括进程管理、内存管理、文件系统、设备管理等内容。',
  },
  {
    id: 5,
    courseId: 'CS302',
    name: '计算机网络',
    type: '4',
    typeName: '专业课',
    credit: 3.5,
    hours: 56,
    teacher: '钱教授',
    semester: '2024-2025-1',
    description: '本课程介绍计算机网络的基本概念、体系结构和协议，包括物理层、数据链路层、网络层、传输层和应用层等内容。',
  },
]);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref<'add' | 'edit'>('add');
const courseFormRef = ref<FormInstance>();
const courseForm = reactive({
  id: 0,
  courseId: '',
  name: '',
  type: '',
  credit: 3,
  hours: 48,
  teacher: '',
  semester: '',
  description: '',
});

// 表单验证规则
const rules = reactive<FormRules>({
  courseId: [
    { required: true, message: '请输入课程编号', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  type: [{ required: true, message: '请选择课程类型', trigger: 'change' }],
  credit: [{ required: true, message: '请输入学分', trigger: 'blur' }],
  hours: [{ required: true, message: '请输入学时', trigger: 'blur' }],
  teacher: [{ required: true, message: '请输入授课教师', trigger: 'blur' }],
  semester: [{ required: true, message: '请选择开课学期', trigger: 'change' }],
  description: [{ required: true, message: '请输入课程描述', trigger: 'blur' }],
});

// 生命周期钩子
onMounted(() => {
  fetchCourseList();
});

// 获取课程列表
const fetchCourseList = () => {
  // 模拟后端接口请求
  setTimeout(() => {
    // 这里应该是实际的API调用
    // 使用假数据
    total.value = courseList.value.length;
  }, 300);
};

// 获取标签类型
const getTagType = (type: string) => {
  switch (type) {
    case '1':
      return 'danger';
    case '2':
      return 'success';
    case '3':
      return 'info';
    case '4':
      return 'warning';
    default:
      return '';
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchCourseList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.courseId = '';
  searchForm.name = '';
  searchForm.type = '';
  currentPage.value = 1;
  fetchCourseList();
};

// 分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchCourseList();
};

// 当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchCourseList();
};

// 添加课程
const handleAddCourse = () => {
  dialogType.value = 'add';
  resetCourseForm();
  dialogVisible.value = true;
};

// 编辑课程
const handleEdit = (row: any) => {
  dialogType.value = 'edit';
  Object.assign(courseForm, row);
  dialogVisible.value = true;
};

// 删除课程
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该课程信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 模拟删除操作
      const index = courseList.value.findIndex((item) => item.id === row.id);
      if (index !== -1) {
        courseList.value.splice(index, 1);
        total.value -= 1;
        ElMessage.success('删除成功');
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 重置表单
const resetCourseForm = () => {
  courseForm.id = 0;
  courseForm.courseId = '';
  courseForm.name = '';
  courseForm.type = '';
  courseForm.credit = 3;
  courseForm.hours = 48;
  courseForm.teacher = '';
  courseForm.semester = '';
  courseForm.description = '';
};

// 提交表单
const submitForm = async () => {
  if (!courseFormRef.value) return;

  await courseFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 模拟添加操作
        const newCourse = {
          id: Date.now(),
          courseId: courseForm.courseId,
          name: courseForm.name,
          type: courseForm.type,
          typeName: courseTypes.value.find((item) => item.value === courseForm.type)?.label || '',
          credit: courseForm.credit,
          hours: courseForm.hours,
          teacher: courseForm.teacher,
          semester: courseForm.semester,
          description: courseForm.description,
        };
        courseList.value.push(newCourse);
        total.value += 1;
        ElMessage.success('添加成功');
      } else {
        // 模拟编辑操作
        const index = courseList.value.findIndex((item) => item.id === courseForm.id);
        if (index !== -1) {
          const updatedCourse = {
            ...courseList.value[index],
            courseId: courseForm.courseId,
            name: courseForm.name,
            type: courseForm.type,
            typeName: courseTypes.value.find((item) => item.value === courseForm.type)?.label || '',
            credit: courseForm.credit,
            hours: courseForm.hours,
            teacher: courseForm.teacher,
            semester: courseForm.semester,
            description: courseForm.description,
          };
          courseList.value[index] = updatedCourse;
          ElMessage.success('更新成功');
        }
      }
      dialogVisible.value = false;
    } else {
      console.log('验证失败', fields);
    }
  });
};
</script>

<style scoped>
.courses-container {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>